package com.dwxt.sport.admin.controller;

import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.StatusCode;
import com.dwxt.common.util.JwtUtils;
import com.dwxt.sport.admin.service.UserServiceAdmin;
import com.dwxt.sport.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/admin")
@RestController
@Api(tags = {"用户业务接口"})
public class UserControllerAdmin {

    @Autowired
    private UserServiceAdmin userServiceAdmin;


    @ApiOperation(value = "登录", notes = "登录", response = BaseResult.class)
    @PostMapping("/login")
    public BaseResult login(@ApiParam(value = "手机号码", required = true) @RequestParam String phone,
                            @ApiParam(value = "密码", required = true) @RequestParam String password,
                            HttpServletRequest request) {
        User user = userServiceAdmin.login(phone, password);
        if (user != null) {
            String token = JwtUtils.createJWT(user.getId() + ",back", (long) 7 * 24 * 60 * 60 * 1000);
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            session.setMaxInactiveInterval(60 * 60 * 5);
            Map map = new HashMap();
            map.put("user", user);
            map.put("token", token);
            return BaseResult.ok(map);
        } else {
            return BaseResult.build(StatusCode.USERNAME_PASSWORD_WRONG);
        }
    }
}
